package cn.com.startai.smartadh5.processlogic.nmc;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.ArrayList;

import cn.com.startai.smartadh5.datasourceupdate.DataSourceUpdateModule;
import cn.com.startai.smartadh5.db.db.entity.DownloadTable;
import cn.com.startai.smartadh5.db.db.manager.DownloadTableHelper;
import cn.com.startai.smartadh5.db.sp.SPManager;
import cn.com.startai.smartadh5.download.DownloadManager;
import cn.com.startai.smartadh5.extension.config.Config;
import cn.com.startai.smartadh5.extension.entity.ReportErrorMsg;
import cn.com.startai.smartadh5.extension.utils.JSONUtils;
import cn.com.startai.smartadh5.extension.utils.LogUtil;
import cn.com.startai.smartadh5.hotcodeupdate.HotCodeUpdateModule;
import cn.com.startai.smartadh5.locallog.SmartLocalLog;
import cn.com.startai.smartadh5.locallog.entity.LogMsg;
import cn.com.startai.smartadh5.main.activity.PhoneControlActivity;
import cn.com.startai.smartadh5.pluginmanager.server.PluginServer;
import cn.com.startai.smartadh5.processlogic.entity.bean.BroadcastTableDeleteBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.DeviceInfoBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.DownloadProgressBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.HardwareKey;
import cn.com.startai.smartadh5.processlogic.entity.bean.ShowFileTypeBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayListData;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayLoopModeBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayStateChangeBean;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.RemovePlayListBean;
import cn.com.startai.smartadh5.processlogic.entity.event.OnCommand;
import cn.com.startai.smartadh5.processlogic.entity.event.OnLoadFinished;
import cn.com.startai.smartadh5.processlogic.entity.event.OnScreenshot;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayListEvent;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayLoopModeEvent;
import cn.com.startai.smartadh5.processlogic.entity.event.player.PlayStateChangeEvent;
import cn.com.startai.smartadh5.processlogic.entity.event.player.RemovePlayListEvent;
import cn.startai.apkcommunicate.CommunicateType;
import cn.startai.apkcommunicate.StartaiCommunicate;
import cn.startai.apkcommunicate.StartaiCommunicateRecv;

/**
 * Created by Taro on 2017/3/15.
 * 与 NMC 的沟通处理类
 */
public class NmcCommunicateLogic implements StartaiCommunicateRecv {

    @Override
    public void onReceive(Context context, String flag, String msg) {

        LogUtil.d("live", " NmcCommunicateLogic : " + flag);

        Logger.d("flag == " + flag + ";msg == " + msg);

        // NMC 返回 SDCard 路径
        if (CommunicateType.COMMUNICATE_TYPE_SDCARD_PATH.equals(flag)) {
            String sdCardPath = JSON.parseObject(msg).getString("sdcardPath");
            SPManager.getInstance().saveSdcardPath(sdCardPath);
            // record
            ArrayList<String> remarks = new ArrayList<>();
            remarks.add("sdcardPath: " + sdCardPath);
            SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "NMC", "Native", "获得SDCard路径", remarks));
        }

        // NMC 返回设备 设备信息
        if (CommunicateType.COMMUNICATE_TYPE_DEVICE_INFOMATION.equals(flag)) {
            DeviceInfoBean bean = JSONUtils.parseObject(msg, DeviceInfoBean.class);
            String sn = bean.getSn();
            String machineType = String.valueOf(bean.getMachineType());//机器类型
            int screenStatus = bean.getScreenStatus();//屏幕状态，1开0关
            Config.screenOff = (screenStatus == 0);
            if (bean.getGfInfo() != null) {
                Config.curBattery = bean.getGfInfo().getBattery();//当前电量
                Config.isBatteryCharging = bean.getGfInfo().getPower() == 1;//是否正在充电
            }
            String sdcardPath = bean.getSdcardPath();//sd路径
            String localIP = bean.getIp();//本机ip

            SPManager.getManager().put(SPManager.KEY_SCREEN_SHUT_OFF, Config.screenOff);
            SPManager.getInstance().saveSdcardPath(sdcardPath);
            SPManager.getInstance().saveLocalIP(localIP);
            //日志
            ArrayList<String> remarks = new ArrayList<>();
            remarks.add("sn: " + bean.getSn());
            remarks.add("clientId: " + bean.getClientId());
            remarks.add("machineType: " + machineType);
            remarks.add("screenStatus: " + screenStatus);
            remarks.add("sdcardPath: " + sdcardPath);
            remarks.add("本机ip: " + localIP);

            boolean isInitComplete = SPManager.getInstance().isInitSuccess();
            if (!isInitComplete) {
                SPManager.getInstance().saveIsMusicBox("1".equals(machineType));
                SPManager.getManager().put(SPManager.KEY_DEVICE_SN, sn);
                // record
                remarks.add("应用初始化");
                // 通知初始化完成
                EventBus.getDefault().post(new OnLoadFinished());
            }

            SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "NMC", "Native", "获得设备信息", remarks));

            EventBus.getDefault().postSticky(bean);

        }

        // NMC 返回设备内存不足 清理缓存
        if (CommunicateType.COMMUNICATE_TYPE_ROM_LIMIT.equals(flag)) {

            SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "NMC", "Native", "设备内存不足, 清理data资源"));
            DataSourceUpdateModule.doClearData();

        }

        // Nmc 返回替换播表 file 字段
        if (CommunicateType.COMMUNICATE_TYPE_PLAYLIST_DISTRIBUTE_1.equals(flag)) {
            // record
            ArrayList<String> remarks = new ArrayList<>();
            remarks.add("msg: " + msg);
            SmartLocalLog.writeLog(new LogMsg(LogMsg.TYPE_RECEIVED, "NMC", "Native", "替换播表 File 字段", remarks));
            DataSourceUpdateModule.doReplaceBroadcastTable(msg);

        }

        // NMC 返回 MIOF 协议
        if (CommunicateType.COMMUNICATE_TYPE_MIOF.equals(flag)) {

            boolean isHandled = false;
            // msg confirm
            JSONObject msgConfirm = new JSONObject();

            // record remark
            ArrayList<String> remarks = new ArrayList<>();
            // get object
            JSONObject msgObject = JSON.parseObject(msg);
            String msgType = msgObject.getString("msgtype");
            try {
                remarks.add("data: " + msgObject.getJSONObject("content").toString());
            } catch (Exception e) {
                e.printStackTrace();
                Logger.e("JSON解析错误: " + e.getMessage());
                // 回复云端，json解析错误

                ReportErrorMsg errorMsg = new ReportErrorMsg();
                errorMsg.setResult(0);
                errorMsg.setMsgcw(NmcReport.getReportMsgcw(msgObject.getString("msgcw")));
                errorMsg.setToid(msgObject.getString("fromid"));
                errorMsg.setTs(System.currentTimeMillis());
                errorMsg.setMsgtype(msgType);
                JSONObject content = new JSONObject();
                content.put("msg", "JSON解析错误");
                errorMsg.setContent(content);
                EventBus.getDefault().post( errorMsg );

                return;
            } finally {
                //回复 nmc 已收到消息
                msgConfirm.put("msgType", msgType);
                StartaiCommunicate.getInstance().send(context,
                        CommunicateType.COMMUNICATE_TYPE_MIOF_CONFIRM,
                        msgConfirm.toString());
            }

            LogUtil.d("live", " msgType : " + msgType);
            Logger.i("指令==>" + msgType);
            Logger.json(msgObject.toJSONString());

            LogMsg logMsg = new LogMsg(LogMsg.TYPE_RECEIVED, "NMC", "Native", "", remarks);

            // 0x8500 更新 web 系统
            if ("0x8500".equals(msgType)) {
                isHandled = true;
                // record
                logMsg.setContent("更新 web 系统");
                SmartLocalLog.writeLog(logMsg);

                // handler
                HotCodeUpdateModule.doWebUpdate(msgObject);
            }


            // 0x8501 更新 web 文件
            if ("0x8501".equals(msgType)) {
                isHandled = true;
                // record
                logMsg.setContent("更新 web 文件");
                SmartLocalLog.writeLog(logMsg);

                // handler
                HotCodeUpdateModule.doWebFileUpdate(msgObject);
            }

            // 0x8502 播表消息
            if ("0x8502".equals(msgType)) {
                isHandled = true;
                // record
                logMsg.setContent("更新播表消息");
                SmartLocalLog.writeLog(logMsg);

                // handler
                DataSourceUpdateModule.doDataUpdate(msgObject);
            }

            // 0x8506 推送文件
            if ("0x8506".equals(msgType)) {
                isHandled = true;
                // record
                logMsg.setContent("云端推送文件消息");
                SmartLocalLog.writeLog(logMsg);

                // handler
                DataSourceUpdateModule.doFileUpdate(msgObject);
            }

            // 0x8508 云端获得播表列表
            if ("0x8508".equals(msgType)) {
                isHandled = true;
                // record
                logMsg.setContent("云端获得播表历史列表");
                SmartLocalLog.writeLog(logMsg);

                // handler
                DataSourceUpdateModule.doSendHistoryBt(msgObject);
            }

            // 0x8509 云端指定播放指定ID的播表
            if ("0x8509".equals(msgType)) {
                isHandled = true;
                // record
                logMsg.setContent("云端播放指定ID播表");
                SmartLocalLog.writeLog(logMsg);

                // handler
                DataSourceUpdateModule.playActionBt(msgObject);
            }

            // 0x8512 云端删除指定ID的播表
            if ("0x8512".equals(msgType)) {
                isHandled = true;
                // record
                logMsg.setContent("云端删除指定播表");
                SmartLocalLog.writeLog(logMsg);

                // handler
                DataSourceUpdateModule.doDelFiles(msgObject);
            }

            if (!isHandled) {
                // record
                logMsg.setContent("未处理 MIOF 消息, 向下传递!");
                SmartLocalLog.writeLog(logMsg);

                int code = Integer.valueOf(msgType.substring(msgType.indexOf("x") + 1));
                JSONObject messageContent = msgObject.getJSONObject("content");
                String reportId = msgObject.getString("fromid");
                PluginServer.sendPluginMessage(code, messageContent.toString(), reportId);
            }

        }

        // NMC 返回下载进度消息
        if (CommunicateType.COMMUNICATE_TYPE_FS_DOWNLOAD.equals(flag)) {

            DownloadProgressBean bean = JSONUtils.parseObject(msg, DownloadProgressBean.class);

            if (bean.getErrorCode().length() == 0) {
                DownloadManager.onProgress(bean);
                //改变数据库中的进度
                boolean isSuccess = DownloadTableHelper.getInstance().changeProgress(bean);
                if (!isSuccess) {
                    DownloadTableHelper.getInstance().add(DownloadTable.convert(bean));
                    DownloadTableHelper.getInstance().changeProgress(bean);
                }
            } else {
                //现在出错
                DownloadManager.onError(bean);


                boolean isSuccess = DownloadTableHelper.getInstance().changeError(bean);
                if (!isSuccess) {
                    DownloadTableHelper.getInstance().add(DownloadTable.convert(bean));
                    DownloadTableHelper.getInstance().changeError(bean);
                }
            }

            //通知 DownloadActivity 界面，下载进度发生改变
            EventBus.getDefault().post(bean);
        }

        // NMC 返回实体按键消息
        if (CommunicateType.COMMUNICATE_TYPE_KEY.equals(flag)) {

            boolean enabledHardwareKey = SPManager.getManager().getBoolean(SPManager.KEY_ENABLED_HARDWARE_KEY, true);
            if (enabledHardwareKey) {
                int key = JSON.parseObject(msg).getIntValue("keyCode");
                HardwareKey hardwareKey = new HardwareKey(key);

                EventBus.getDefault().post(hardwareKey);
            }
        }

        // NMC 请求截图
        if (CommunicateType.COMMUNICATE_TYPE_SCREENSHOT.equals(flag)) {
            OnScreenshot onScreenshot = JSON.parseObject(msg, OnScreenshot.class);
            EventBus.getDefault().post(onScreenshot);
            Logger.i("NMC 截屏");
        }

        // NMC 语音指令   云端操控播表
        if (CommunicateType.COMMUNICATE_TYPE_VOICE_CONTROL.equals(flag)) {
            OnCommand onCommand = JSON.parseObject(msg, OnCommand.class);
            if (onCommand.getCmd() == CommunicateType.COMMUNICATE_TYPE_KEY_PLAY) {
                new Handler().postDelayed(() -> EventBus.getDefault().post(onCommand), 1200);
            } else {
                getTopStackState();
                EventBus.getDefault().post(onCommand);
            }
        }

        //NMC 删除播表
        if (CommunicateType.COMMUNICATE_TYPE_DELETE_PLAYLIST.equals(flag)) {
            JSONObject delete = JSON.parseObject(msg);
            EventBus.getDefault().post(new BroadcastTableDeleteBean(delete.getString("id")));
        }

        //播放相关==================================================================================
        //播放列表
        if(CommunicateType.COMMUNICATE_TYPE_MEDIA_PLAYLIST_CHANGE.equals(flag)) {
            StartaiCommunicate.getInstance().send(context,
                    CommunicateType.COMMUNICATE_TYPE_MEDIA_PLAYLIST_CHANGE,
                    msg);
            Log.i("NmcComm",  "json ="+msg);
            PlayListData playListData = JSONUtils.parseObject(msg, PlayListData.class);
            //判断栈顶的Activity
             getTopStackState();
            EventBus.getDefault().post(new PlayListEvent(playListData));

        }

        //改变播放状态
        if(CommunicateType.COMMUNICATE_TYPE_MEDIA_PLAYSTATUS_CHANGE.equals(flag)) {
//            StartaiCommunicate.getInstance().send(context,
//                    CommunicateType.COMMUNICATE_TYPE_MEDIA_PLAYSTATUS_CHANGE,
//                    msg);
            PlayStateChangeBean bean = JSONUtils.parseObject(msg, PlayStateChangeBean.class);
            EventBus.getDefault().post(new PlayStateChangeEvent(bean));
        }

        //删除播放列表中的某个视频
        if(CommunicateType.COMMUNICATE_TYPE_MEDIA_PLAYLIST_REMOVE.equals(flag)) {
            StartaiCommunicate.getInstance().send(context,
                    CommunicateType.COMMUNICATE_TYPE_MEDIA_PLAYLIST_REMOVE,
                    msg);
            RemovePlayListBean bean = JSONUtils.parseObject(msg, RemovePlayListBean.class);
            EventBus.getDefault().post(new RemovePlayListEvent(bean));
        }

        //切换循环播放模式
        if(CommunicateType.COMMUNICATE_TYPE_DEDIA_PLAYMODE.equals(flag)) {
            StartaiCommunicate.getInstance().send(context,
                    CommunicateType.COMMUNICATE_TYPE_DEDIA_PLAYMODE,
                    msg);
            PlayLoopModeBean bean = JSONUtils.parseObject(msg, PlayLoopModeBean.class);
            EventBus.getDefault().post(new PlayLoopModeEvent(bean));
        }
        //移动端查看文件类型
        else if (CommunicateType.COMMUNICATE_TYPE_SHOW_FILETYPE_LIST.equals(flag)){
            StartaiCommunicate.getInstance().send(context,
                    CommunicateType.COMMUNICATE_TYPE_SHOW_FILETYPE_LIST,
                    msg);
            ShowFileTypeBean bean =JSONUtils.parseObject(msg,ShowFileTypeBean.class);
            try {
                org.json.JSONObject jsonObject =new org.json.JSONObject(msg);
                String path =  jsonObject.getString("path");
                String s=  path.substring(path.lastIndexOf("/")+1);
                SPUtils.getInstance().put("pathValue",s);
                Log.i("NmcComm","s = "+s);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            EventBus.getDefault().post(bean);

//            Intent intent = new Intent(context, PhoneControlActivity.class);
//            intent.putExtra("ShowFileTypeBean", bean);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(intent);

        }

    }
    public void getTopStackState(){
        Activity topActivity = ActivityUtils.getTopActivity();
        String localClassName = topActivity.getLocalClassName();
        Log.i("NmcComm", "localClassName = " + localClassName);
        if (localClassName.lastIndexOf(PhoneControlActivity.class.getSimpleName()) > 0) {
            topActivity.finish();
        }
    }

}
